package com.heny.demo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heny.demo.entity.PointData;
import com.heny.demo.entity.TurnPoint;
import com.heny.demo.mapper.PointMapper;
import com.heny.demo.service.FileImportService;
import com.heny.demo.util.FileImportStrategy;
import com.heny.demo.util.FileImportStrategyFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.stream.Collectors;


/**
 * @author yaonn
 * @date 2025/9/1123:47
 * @Description
 */
@Service
public class FileImportServiceImpl extends ServiceImpl<PointMapper, TurnPoint> implements FileImportService {
    private final FileImportStrategyFactory strategyFactory;

    @Autowired
    public FileImportServiceImpl(FileImportStrategyFactory strategyFactory) {
        this.strategyFactory = strategyFactory;
    }


    @Override
    public void importFile(MultipartFile file) throws Exception {
        String fileName = file.getOriginalFilename();
        String fileType = getFileExtension(fileName);
        // 获取合适的策略
        FileImportStrategy strategy = strategyFactory.getStrategy(fileType);

        // 导入数据
        List<PointData> locationDataList = strategy.importData(file.getInputStream());

        // 转换为实体并保存
        List<TurnPoint> entities = locationDataList.stream()
                .map(data -> new TurnPoint(data.toPoint(),data.getName()))
                .collect(Collectors.toList());

        saveBatch(entities);
    }
    private String getFileExtension(String fileName) {
        int dotIndex = fileName.lastIndexOf('.');
        return (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1);
    }
}
